package com.forum.service.impl;

import com.forum.mapper.RoleMapper;
import com.forum.mapper.UserRoleMapper;
import com.forum.model.entity.Role;
import com.forum.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色服务实现类
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {
    
    private final RoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;
    
    @Override
    public List<Role> getAllRoles() {
        return roleMapper.selectList(null);
    }
    
    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return roleMapper.selectByUserId(userId);
    }
    
    @Override
    public boolean hasRole(Long userId, String roleCode) {
        return userRoleMapper.countByUserIdAndRoleCode(userId, roleCode) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRoles(Long userId, List<Long> roleIds) {
        // 先删除用户现有的角色关联
        userRoleMapper.deleteByUserId(userId);
        
        // 然后批量插入新的角色关联
        if (roleIds != null && !roleIds.isEmpty()) {
            userRoleMapper.batchInsert(userId, roleIds);
        }
    }
    
    @Override
    public List<String> getRoleCodesByUserId(Long userId) {
        List<Role> roles = getRolesByUserId(userId);
        return roles.stream()
            .map(Role::getCode)
            .collect(Collectors.toList());
    }
} 